#include "PySourceSetter.h"
#include "Socket.h"
#include "PyPacketFilter.h"

PySourceSetter::PySourceSetter(Socket& sock, PyPacketFilter& pyPacketFilter, PacketCapture<SendPacket<PyPacketFilter> >& packetCapture)
	: m_socket(sock)
	, m_pyPacketFilter(pyPacketFilter)
	, m_packetCapture(packetCapture)
{
}

PySourceSetter::~PySourceSetter()
{
}

void PySourceSetter::operator()()
{
	while(true)
	{
		int strlen = 0;

		// Receive the new python source string length
		if(m_socket.ReceiveFully(&strlen, sizeof(strlen)) != 0)
		{
			m_socket.Close();
			m_packetCapture.Stop();
			return;
		}
		strlen = ntohl(strlen);

		// Receive the whole python source
		char *buf = new char[strlen + 1];
		int ret = m_socket.ReceiveFully(buf, strlen);
		if(ret != 0)
		{
			m_socket.Close();
			m_packetCapture.Stop();
			delete[] buf;
			return;
		}
		buf[strlen] = '\0';

		// Set the new python source to python packet filter
		if(!m_pyPacketFilter.SetPySourceFilter(buf))
		{
			m_socket.Close();
			m_packetCapture.Stop();
			delete[] buf;
			printf("Compile remote python source error\n");
			return;
		}
		delete[] buf;
	}
}
